package com.xxx.kjds.controller;

import com.xxx.kjds.entity.User;
import com.xxx.kjds.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/userLogin", method = RequestMethod.POST)
    @ResponseBody
    public String userLogin(HttpServletRequest request, HttpSession session) {
        //System.out.println(request);
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //System.out.println(name+ password);
        User user = userService.checkLogin(username, password);

        if (user != null) {
            session.setAttribute("user", user);
            session.setAttribute("status", "logined");
            session.setAttribute("id", user.getId());
            session.setAttribute("name", user.getName());
            session.setAttribute("password", user.getPassword());
            session.setAttribute("account_type", user.getAccountType());
            session.setAttribute("email", user.getEmail());
            session.setAttribute("phone", user.getPhone());
            session.setAttribute("company_id", user.getCompanyId());
            session.setAttribute("menu_id", user.getMenuId());
            return "success";
        } else {
            return "fail";
        }
    }


    @RequestMapping("/logout")
    @ResponseBody
    public String logout(HttpServletRequest request, HttpServletResponse response,
                         HttpSession session) {
        if (session != null) {
            session.invalidate();
        }
        return "success";
    }
}
